export default {
	namespaced: true,
	// 相当于data数据
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	// 相当于方法
	mutations: {
		// adddCart方法把当前商品添加到cart数据里面
		addCart(state, goods) {
			// 如果外界传过来的商品的id 等于 数组里面的商品的id 吧返回值赋给findResult
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)

			if (!findResult) {
				// 没找到,商品信息对象push到cart里面
				state.cart.push(goods)
			} else {
				// 找到了
				findResult.goods_count++
			}
			this.commit('my_cart/saveToStorage')

		},
		updateGoodsState(state, good) {

			// 首先找到传过来的good_id与state里的good_idd对应的Result
			const Result = state.cart.find(x => x.goods_id === good.goods_id)
			if (Result) {
				Result.goods_state = good.goods_state
				this.commit('my_cart/saveToStorage')
			}


		},
		updateGoodsCount(state, good) {
			// 查找点击的good_id
			const Result = state.cart.find(x => x.goods_id === good.goods_id2)
			// 如果找到goods_id了
			if (Result) {
				// 更新当前cart里的count的值
				Result.goods_count = good.goods_count
				this.commit('my_cart/saveToStorage')
			}
		},
		// 更新购物车中所有勾选状态
		updateAllGoodsState(state, newState) {

			state.cart.forEach(x => x.goods_state = newState)

			this.commit('my_cart/saveToStorage')
		},
		deleteGoodsItem(state, good) {
			// 查找点击的good_id
			const Result = state.cart.find(x => x.goods_id === good.goods_id3)
			// 如果找到goods_id了
			if (Result) {
				// 更新当前cart里的count的值
				state.cart = state.cart.filter(item => item != Result)
				this.commit('my_cart/saveToStorage')
			}
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		// 更新购物车中所有勾选状态
		updateAllGoodsState(state, newState) {

			state.cart.forEach(x => x.goods_state = newState)

			this.commit('my_cart/saveToStorage')
		}
		},
	// 对state里面的数据进行加工处理
		getters: {
			// 购物车中所有商品的总数量
			total(state) {

				return state.cart.reduce((total, item) => total += item.goods_count, 0)
			},
			// 购物车中所勾选商品的总数量
			checkCount(state) {

				return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
			},
			checkPrice(state) {

				return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price,
					0).toFixed(2)
			}


		}	
	
}
